package com.atgugu.flink.chapter07.timer;

import com.atgugu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lzc
 * @Date 2022/4/6 10:02
 */
public class Flink01_Timer_ProcessingTime {
    public static void main(String[] args) throws Exception {
        
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        
        // 当水位超过20的时候, 5s之后发出预警
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .keyBy(WaterSensor::getId) // 如果要用定时器, 必须先keyBy 因为定时器是和key相关
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
    
                private long ts;
    
                // 当定时器触发的执行这个方法
                @Override
                public void onTimer(long timestamp,  // 定时器触发的时间
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    out.collect(ctx.getCurrentKey() + " 水位超过 20, 发出预警信息...");
                }
    
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    
                    if (value.getVc() > 20) {
                        
                        ts = System.currentTimeMillis() + 5000;
                        // 注册一个基于处理时间的定时器
                        // 参数: 就是定时器触发的时间
                        // 注册一个定时器只会触发一次
                        System.out.println("注册定时器: " + ts);
                        ctx.timerService().registerProcessingTimeTimer(ts);
                    }else if(value.getVc() == 10){
                        System.out.println("取消定时器: " + ts);
                        ctx.timerService().deleteProcessingTimeTimer(ts);
                    }
                    
                    
                }
            })  // 定时器只能用在process中, 因为这里才有context
            .print();
        
        
        env.execute("flink_timer");
        
        
    }
}
